public class LeetCode1004 {
    public int longestOnes(int[] nums, int k) {
        int countZero = 0;
        for (int i : nums) {//统计0的个数
            if (i == 0) {
                countZero++;
            }
        }
        k = Math.min(k, countZero);
        int K = k;
        int left = 0;
        int right = 0;
        int n = nums.length;
        int len = 0;
        while (right < n) {
            right++;
            if (right >= n) {
                break;
            }
            while (right < n &&nums[right] == 0 && k > 0) {
                k--;
                right++;
            }
            len = Math.max(len, right - left);
            while (left < right) {
                left++;
            }
            k = K;
        }

        return len;
    }

    public int longestOnes2(int[] nums, int k) {
        int right = 0;
        int left = 0;
        int countZero = 0;
        int n = nums.length;
        int len = 0;
        while (right < n) {
            if (nums[right] == 0) {
                countZero++;
            }
            right++;
            while (countZero > k) {
                if (nums[left] == 0) {
                    countZero--;
                }
                left++;
            }
            len = Math.max(len, right - left);
        }

        return len;
    }
}
